using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Win32.Dialogs;
using System;
using System.Threading.Tasks;
using System.Linq;
using ArtOfTest.Common.Win32;
using System.Collections.Generic;

namespace Tests
{
	class ChromeLauncher : IDisposable
	{
		readonly Manager browserManager;

		public ChromeLauncher(Manager browserManager)
		{
			this.browserManager = browserManager;
		}

		public async Task<Chrome> Launch()
		{
			await Task.Run(() => browserManager.LaunchNewBrowser());
			var browser = browserManager.ActiveBrowser;
			browser.Closing += (sender, e) => CloseDialogs(browser);

			return new Chrome(browser);
		}

		void CloseDialogs(Browser browser)
		{
			var allDialogs = DialogMonitor.GetAllDialogs().Cast<Window>();
			var browserWindow = browser.Window;
			var childDialogs = allDialogs.Where(window => window.IsChildOf(browserWindow));
			childDialogs.ForEach(dialog => dialog.Close());
		}

		public void Dispose()
		{
			foreach (var browser in browserManager.Browsers)
				browser.Close();
			browserManager.Dispose();
		}
	}
}
